<template>
    <div id="password-reset-container">
        <el-form ref="formRef" v-loading="loading" :model="formData" :rules="rules" label-width="110px" status-icon
            class="reset-form">
            <el-form-item label="ID：" prop="id">
                <el-input id="password-reset-container-user-id-input" :value="formData.id" disabled
                    placeholder="请输入用户ID获取用户信息" />
            </el-form-item>
            <el-form-item label="真实姓名：" prop="name">
                <el-input id="password-reset-container-user-name-input" :value="formData.name" disabled
                    placeholder="请输入用户ID获取用户真实姓名" />
            </el-form-item>
            <el-form-item label="用户名称：" prop="username">
                <el-input id="password-reset-container-user-username-input" :value="formData.username" disabled
                    placeholder="请输入ID获取用户名称" />
            </el-form-item>
            <el-form-item label="新密码：" prop="newPassword">
                <el-input id="password-reset-container-new-password-input" v-model="formData.newPassword"
                    type="password" placeholder="请输入新密码" show-password />
                <!-- <div class="password-tip">8-16个字符，必须包含英文、数字、特殊字符</div> -->
            </el-form-item>
            <el-form-item label="确认新密码：" prop="confirmPassword">
                <el-input id="password-reset-container-confirm-password-input" v-model="formData.confirmPassword"
                    type="password" placeholder="再次输入新密码" show-password />
            </el-form-item>
            <el-form-item>
                <div class="button-group">
                    <el-button id="password-reset-container-confirm-button" type="primary"
                        @click="handleSubmit(formRef)" :disabled="!canSubmit">确定</el-button>
                    <el-button id="password-reset-container-cancel-button" @click="handleCancel">取消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updatePassword, getUserInfo as getUserInfoApi } from '@/api'
import { useRouter, useRoute } from 'vue-router'
import { useLoginStore } from '@/store/login'
const loginStore = useLoginStore()
const router = useRouter()
const route = useRoute()
const formRef = ref(null)

// 表单数据
const formData = reactive({
    id: '',
    // id: '1863938488714407938',
    name: '',
    username: '',
    newPassword: '',
    confirmPassword: ''
})
watch(() => route.params.userId, () => {
    formData.id = route.params.userId
    getUserInfo()
})
const loading = ref(false)

// 密码验证规则
const validatePassword = (rule, value, callback) => {
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,16}$/
    if (!value) {
        callback(new Error('请输入密码'))
    } else if (!passwordRegex.test(value)) {
        callback(new Error('密码必须包含英文、数字和特殊字符，长度8-16位'))
    } else {
        callback()
    }
}

// 确认密码验证规则
const validateConfirmPassword = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请再次输入密码'))
    } else if (value !== formData.newPassword) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

// 表单验证规则
const rules = reactive({
    id: [
        { required: true, message: '请输入用户ID', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '未获取到用户信息', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '未获取到用户信息', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 8, message: '密码最少8位', trigger: 'blur' },
        { max: 20, message: '密码最多20位', trigger: 'blur' }

    ],
    confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' },
        { min: 8, message: '密码最少8位', trigger: 'blur' },
        { max: 20, message: '密码最多20位', trigger: 'blur' }
    ]
})

const canSubmit = computed(() => {
    return formData.id && formData.name && formData.username && formData.newPassword && formData.confirmPassword
})

// 提交表单
const handleSubmit = async (formEl) => {
    // console.log(formEl)
    const isMe = loginStore.userInfo.data.userId == formData.id
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const data = {
                userId: formData.id,
                password: formData.newPassword
            }
            try {
                loading.value = true
                const res = await updatePassword(data)
                if (res.data.code !== 200) {
                    ElMessage.error('密码重置失败')
                } else {
                    // 如果重置的是自己，则需要退出登录
                    if (isMe) {
                        loginStore.clearLoginInfo()
                        ElMessage.success('密码重置成功，请重新登录')
                        router.replace('/login')
                        return
                    }
                    ElMessage.success('密码重置成功')
                    router.back()
                }
            } catch (error) {
                ElMessage.error('密码重置失败')
            } finally {
                loading.value = false
            }
        } else {
            console.log('error submit:', fields)
        }
    })
}

// 取消
const handleCancel = () => {
    formRef.value.clearValidate()
    formData.newPassword = ''
    formData.confirmPassword = ''
    router.back()
}

const getUserInfo = async () => {
    const id = formData.id
    formData.name = ''
    formData.username = ''
    try {
        loading.value = true
        const res = await getUserInfoApi(id)
        if (res.data.code !== 200) return
        const userInfo = res.data.data
        formData.name = userInfo.name
        formData.username = userInfo.username
    } catch (error) {
        ElMessage.error('获取用户信息失败')
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    if (route.params.userId) formData.id = route.params.userId
    getUserInfo()
})
</script>

<style lang="less" scoped>
#password-reset-container {
    .reset-form {
        width: min(100%, 480px);
        height: 100%;
        margin: auto auto 50vh;
        transform: translateY(50%);
        position: relative;

        // .password-tip {
        //     font-size: 12px;
        //     color: #909399;
        //     margin-top: 18px;
        //     line-height: 1.2;
        // }

        .button-group {
            display: flex;
            justify-content: center;
            gap: 20px;
        }
    }
}
</style>
